<script lang="ts" setup>
import { defineProps, withDefaults, ref, computed } from 'vue';
import { IContributorVo } from '@/api/dto/contributors';
import { GITEE_NO_PORTRAIT_URL } from '@/utils/constants';

const props = withDefaults(defineProps<{
  contributors: IContributorVo[]
  name: string,
  customizeClass?: string
}>(), { customizeClass: '' });
// 跳转到gitee主页
const toProfile = (username: string) => {
  window.open(`https://gitee.com/${username}`, '_blank');
};
// 是否展示颜色首字母头像，默认图片头像
const isShow = ref<boolean>(true);
// 头像随机颜色集合
const randomColors = ref<Array<string>>(['#9254DE', '#096DD9', '#08979C', '#389E0D', '#FA8C16']);
// img渲染错误时，加载默认图片
const loadedError = async () => {
  isShow.value = false;
};
// 根据首字母的ASCII码挑选背景颜色
const pickColor = computed<string>(() => {
  const codeNum = props.contributors.find(item => item.username === props.name)?.nickname.charCodeAt(0);
  // 获取颜色，只有三种情况
  const remainder = ((codeNum || 0) % 10) % 5;
  return randomColors.value[remainder];
});
</script>
<template>
  <div class="member-info-viewer">
    <div
      :class="['avatar',props.customizeClass ? props.customizeClass:'']"
      @click="toProfile(props.name)"
      v-if="isShow&&(props.contributors.find(item=>item.username===props.name)?.avatarUrl!==GITEE_NO_PORTRAIT_URL)"
    >
      <img
        referrer="no-referrer|origin|unsafe-url"
        :src="props.contributors.find(item=>item.username===props.name)?.avatarUrl"
        @error="loadedError"
      >
    </div>
    <div
      :class="['avatar error',props.customizeClass ? props.customizeClass:'']"
      :style="{backgroundColor:pickColor}"
      @click="toProfile(props.name)"
      v-else
    >
      {{ props.contributors.find(item => item.username === props.name)?.nickname.slice(0, 1).toUpperCase() }}
    </div>
    <jm-text-viewer :value='props.contributors.find(item=>item.username===props.name)?.nickname' class="name"/>
  </div>
</template>
<style lang="less" scoped>
.member-info-viewer {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;

  .avatar {
    border-radius: 50%;
    overflow: hidden;

    &.error {
      display: flex;
      align-items: center;
      justify-content: center;
      color: #FFFFFF;
    }

    img {
      width: 100%;
    }
  }

  .name {
    margin-top: 5px;
    width: 100%;
  }

  ::v-deep(.jm-text-viewer) {
    .content {
      .text-line {
        text-align: center;
      }
    }
  }
}
</style>
